#include "ukuiwindow.h"
#include "ukuiwindowmanager.h"
#include "ukuiwindowpicker.h"

#include <QApplication>
#include <QDir>
#include <QLoggingCategory>
#include <QScreen>

#include <sys/stat.h>

using namespace ukuiwaylandclient;

void setupEnvironment()
{
    auto xdg_runtime_dir = QString::fromUtf8(qgetenv("XDG_RUNTIME_DIR"));
    if (xdg_runtime_dir.isEmpty())
        return;

    QDir runtimeDir(xdg_runtime_dir);
    QStringList socketList;
    while (true) {
        for (const QFileInfo &socket : runtimeDir.entryInfoList(QDir::System | QDir::NoDotAndDotDot)) {
            if (socket.fileName().startsWith("wayland-")) {
                struct stat st;
                if (stat(socket.absoluteFilePath().toUtf8().constData(), &st) == 0 && S_ISSOCK(st.st_mode)) {
                    socketList.append(socket.fileName());
                }
            }
        }
        if (!socketList.isEmpty())
            break;
    }

    if (!socketList.isEmpty()) {
        qputenv("QT_QPA_PLATFORM", "wayland");
        qputenv("WAYLAND_DISPLAY", socketList.first().toUtf8());
    }
}

int main(int argc, char *argv[])
{
    setupEnvironment();

    // disenable debug output
    QApplication app(argc, argv);
    UkuiWindowManager *windowManager = new UkuiWindowManager();

    const auto screens = QGuiApplication::screens();
    if (screens.isEmpty()) {
        qWarning() << "No screens available!";
        return -1;
    }

    // Create the window picker widget
    QList<UkuiWindowPicker *> pickers;
    for (const auto &screen : screens) {
        UkuiWindowPicker *picker = new UkuiWindowPicker(windowManager);
        picker->setGeometry(screen->geometry());
        picker->show();
        pickers.append(picker);
        QObject::connect(picker, &UkuiWindowPicker::windowSelected, [pickers, picker, windowManager](const QPoint &position) {
            UkuiWindow *selectedWindow = windowManager->findWindowOnPosition(position + picker->pos());
            qDebug(UKUIWAYLANDPROP) << selectedWindow;
            exit(0);
        });
    }

    return app.exec();
}